package com.yanqu.road.server.agent.inter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.entity.enums.eAgentErrorCode;
import com.yanqu.road.entity.enums.eUnionPosition;
import com.yanqu.road.entity.union.UnionInfo;
import com.yanqu.road.entity.union.cross.CrossUnionInfo;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.pb.union.UnionProto;
import com.yanqu.road.pb.union.cross.CrossUnionProto;
import com.yanqu.road.server.agent.AgentInterfaceMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.string.StringUtils;

import java.util.*;

/**
 * @Author wpj
 * @Date 2021/4/7
 */
public class AgentUnion {
    /**
     * 修改商会信息
     */
    public String changeUnionInfo(JSONObject param) {
        JSONObject ret = AgentInterfaceMgr.getDefaultRet();

        String unionUid = param.getString("unionUid");
        String unionName = param.getString("unionName");
        String outNotice = param.getString("outNotice");
        String innerNotice = param.getString("innerNotice");
        String qqCode = param.getString("qqCode");
        String wechatCode = param.getString("wechatCode");
        int joinLimit = 0;
        if(param.containsKey("joinLimit")){
            joinLimit = param.getIntValue("joinLimit");
        }
        int level = 0;
        if(param.containsKey("level")){
            level = param.getIntValue("level");
        }

        UnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
        if (unionInfo == null) {
            ret.put("msg", "找不到商会");
            return ret.toString();
        }
        CrossUnionProto.CrossUnionModifyFromAdminMsg.Builder msg = CrossUnionProto.CrossUnionModifyFromAdminMsg.newBuilder();
        msg.setUnionName(unionName);
        msg.setOutNotice(outNotice);
        msg.setInnerNotice(innerNotice);
        if(!StringUtils.isNullOrEmpty(qqCode)){
            msg.setQqCode(qqCode);
        }
        msg.setWtCode(wechatCode);
        msg.setUnionUid(unionUid);
        if(joinLimit > 0){
            msg.setJoinLimit(joinLimit);
        }if(level > 0){
            msg.setLevel(level);
        }
        GamePlayerMgr.sendPacket(0, YanQuMessageUtils.buildMessage(Protocol.C_UNION_MODIFY_FROM_ADMIN, msg));

//        synchronized (CrossUnionMgr.getLockObj()) {
//            unionInfo.setUnionName(unionName);
//            MonopolyMarketMgr.changeUnionName(unionUid,unionName);
//            unionInfo.setOutNotice(outNotice);
//            unionInfo.setInnerNotice(innerNotice);
//            unionInfo.setQqCode(qqCode);
//            unionInfo.setWechatCode(wechatCode);
//        }
        AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
        return ret.toString();
    }

    public String getUnionInfoList(JSONObject param) {
        JSONObject ret = AgentInterfaceMgr.getDefaultRet();
        List<UnionInfo> allUnionInfos = new ArrayList<>();
        allUnionInfos.addAll(CrossUnionMgr.getUnionInfoMap().values());
        allUnionInfos.addAll(CrossUnionMgr.getDeleteUnionInfoMap().values());
        List<UnionInfo> resultUnionInfos = new ArrayList<>();
        String unionUid = param.getString("unionUid");
        String unionAliasId = param.getString("unionAliasId");
        String unionName = param.getString("unionName");
        String curPage = param.getString("curPage");
        String perNum = param.getString("perNum");
        int orderBy = 0; //排序类型 0 赚钱  1创建时间
        if(param.containsKey("orderBy")){
            orderBy = param.getIntValue("orderBy");
        }
        int orderType = 0; //升降序  0 倒叙  1 升序
        if(param.containsKey("orderType")){
            orderType = param.getIntValue("orderType");
        }
        for (UnionInfo unionInfo : allUnionInfos) {
            if (!StringUtils.isNullOrEmpty(unionUid)) {
                if (!Objects.equals(unionInfo.getUnionUid(), unionUid)) {
                    continue;
                }
            }
            if (!StringUtils.isNullOrEmpty(unionAliasId)) {
                if (unionInfo.getUnionAliasId() != Long.parseLong(unionAliasId)) {
                    continue;
                }
            }
            if (!StringUtils.isNullOrEmpty(unionName)) {
                if (!unionInfo.getUnionName().contains(unionName)) {
                    continue;
                }
            }
            resultUnionInfos.add(unionInfo);
        }
        Comparator comparator = Comparator.comparing(UnionInfo::getTotalEarnSpeed);
        if(orderBy == 1){
            comparator = Comparator.comparingLong(UnionInfo::getCreateTime);
        }
        if(orderType == 0){
            comparator = comparator.reversed();
        }
        resultUnionInfos.sort(comparator);
        List<UnionInfo> pageUnionInfos = new ArrayList<>();
        int startPos = (Integer.parseInt(curPage) - 1) * Integer.parseInt(perNum);
        int endPos = Integer.parseInt(perNum) * Integer.parseInt(curPage) - 1;
        for (int i = startPos; i < resultUnionInfos.size() && i < endPos; i++) {
            pageUnionInfos.add(resultUnionInfos.get(i));
        }
        int allCount = resultUnionInfos.size();
        int pageNum = resultUnionInfos.size() / Integer.parseInt(perNum);
        if (resultUnionInfos.size() % Integer.parseInt(perNum) > 0) {
            pageNum++;
        }
        JSONObject resultData = new JSONObject();
        resultData.put("items", JSON.toJSONString(pageUnionInfos));
        JSONObject pageJson = new JSONObject();
        pageJson.put("p", curPage);
        pageJson.put("a", pageNum);
        pageJson.put("c", allCount);
        resultData.put("page", pageJson.toJSONString());
        AgentInterfaceMgr.setData(ret, resultData.toJSONString());
        AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
        return ret.toString();
    }

    /**
     * 商会成员信息
     */
    public String getUnionMemberList(JSONObject param) {
        JSONObject ret = AgentInterfaceMgr.getDefaultRet();
        String unionUid = param.getString("unionUid");
        Map<Long, CrossUnionMember> memberMap = CrossUnionMgr.getUnionMemberMap(unionUid);
        if(memberMap == null){
            ret.put("msg", "找不到商会");
            return ret.toString();
        }
        List<CrossUnionMember> list = new ArrayList<>(memberMap.values());
        JSONObject resultData = new JSONObject();
        JSONArray array = new JSONArray();
        for (CrossUnionMember member : list) {
            JSONObject object = new JSONObject();
            object.put("id", member.getUserId());
            object.put("name", member.getUserBaseInfo().getNickName());
            object.put("title", member.getUserBaseInfo().getTitleId());
            object.put("earnSpeed", member.getUserBaseInfo().getEarnSpeed().toString());
            object.put("totalCont", member.getTotalContribution());
            object.put("pos", member.getPosition());
            object.put("todayCont", member.getTodayContribution());
            object.put("quitTime", member.getQuitTime());
            object.put("kickTime", member.getKickTime());
            object.put("joinTime", member.getJoinTime());
            object.put("dayKickNum", member.getDayKickNum());
            object.put("historyMaxAbility", member.getHistoryMaxAbility().toString());
            array.add(object);
        }
        resultData.put("items", array);
        AgentInterfaceMgr.setData(ret, resultData.toJSONString());
        AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
        return ret.toJSONString();
    }

    /**
     * 解散商会
     */
    public String deleteUnion(JSONObject param) {
        JSONObject ret = AgentInterfaceMgr.getDefaultRet();

        String unionUid = param.getString("unionUid");


        CrossUnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
        if (unionInfo == null) {
            ret.put("msg", "找不到商会");
            return ret.toString();
        }

        GamePlayer player = GamePlayerMgr.getPlayer(unionInfo.getMasterUserId());
        if (player == null) {
            ret.put("msg", "没找到会长");
            return ret.toString();
        }
        //int retInt = UnionMgr.deleteUnion(player);
        player.sendPacket(Protocol.C_UNION_DELETE, UnionProto.CrossUnionDeleteReqMsg.newBuilder().setCanDeleteUnionRet(0));

        int retInt = 0;
        if (retInt == 0) {
            AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
        } else {
            ret.put("msg", "解散失败");
            ret.put("status", retInt);
            return ret.toString();
        }

        return ret.toString();
    }

    /**
     * 转让商会
     */
    public String transferUnion(JSONObject param) {
        JSONObject ret = AgentInterfaceMgr.getDefaultRet();

        String unionUid = param.getString("unionUid");
        long userId = Long.valueOf(param.getString("userId"));


        UnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
        if (unionInfo == null) {
            ret.put("msg", "找不到商会");
            return ret.toString();
        }

        GamePlayer player = GamePlayerMgr.getPlayer(unionInfo.getMasterUserId());
        if (player == null) {
            ret.put("msg", "找不到转让的玩家");
            return ret.toString();
        }

        //int retInt = UnionMgr.setMemberPosition(player, userId, eUnionPosition.Master.getValue(), true);
        int retInt = 0;

        CrossUnionProto.UnionPositionSetCrossReqMsg.Builder crossReq = CrossUnionProto.UnionPositionSetCrossReqMsg.newBuilder().setPosition(eUnionPosition.Master.getValue()).setUserId(userId);
        crossReq.setIsBack(true);
        player.sendPacket(Protocol.C_UNION_POSITION_SET, crossReq);

        if (retInt == 0) {
            AgentInterfaceMgr.setCommonRet(ret, eAgentErrorCode.Success.getValue());
        } else {
            ret.put("msg", "转让失败");
            ret.put("status", retInt);
            return ret.toString();
        }
        return ret.toString();
    }


}
